package cn.edu.nju.myweibo.activity;

import java.io.IOException;
import java.util.Iterator;

import cn.edu.nju.myweibo.json.JsonParser;
import cn.edu.nju.myweibo.model.User;
import cn.edu.nju.myweibo.model.Weibo;

import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.StatusesAPI;
import com.weibo.sdk.android.api.WeiboAPI.FEATURE;
import com.weibo.sdk.android.keep.AccessTokenKeeper;
import com.weibo.sdk.android.net.RequestListener;

import android.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;

public class MainActivity extends Activity {

	private com.weibo.sdk.android.Weibo myWeibo;
	private static final String CONSUMER_KEY = "1431017657";
	private static final String REDIRECT_URL = "https://api.weibo.com/oauth2/default.html";
	public static Oauth2AccessToken accessToken;
	private boolean hasOriginal = false;
	private boolean hasRetweeted = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		myWeibo = com.weibo.sdk.android.Weibo.getInstance(CONSUMER_KEY, REDIRECT_URL);
		accessToken = AccessTokenKeeper.readAccessToken(this);
		if (accessToken.isSessionValid()) {
			init();
		} else {
			myWeibo.authorize(MainActivity.this, new AuthDialogListener());
		}
	}

	private void init() {
		setContentView(R.layout.activity_main);
		setMenuListener();
		setHome();
	}

	private void clearMenu() {

		ImageButton home = (ImageButton) findViewById(R.id.home);
		home.setBackgroundColor(getResources().getColor(R.color.dark_theme));

		ImageButton message = (ImageButton) findViewById(R.id.message);
		message.setBackgroundColor(getResources().getColor(R.color.dark_theme));

		ImageButton friends = (ImageButton) findViewById(R.id.friends);
		friends.setBackgroundColor(getResources().getColor(R.color.dark_theme));

		ImageButton search = (ImageButton) findViewById(R.id.search);
		search.setBackgroundColor(getResources().getColor(R.color.dark_theme));

		ImageButton settings = (ImageButton) findViewById(R.id.settings);
		settings.setBackgroundColor(getResources().getColor(R.color.dark_theme));

	}

	private void clearContent() {
		LinearLayout tab_layout = (LinearLayout) findViewById(R.id.tab_layout);
		tab_layout.removeAllViews();
	}

	private void setMenuListener() {
		ImageButton home = (ImageButton) findViewById(R.id.home);
		home.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {     
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					clearMenu();
					v.setBackgroundColor(getResources().getColor(R.color.dark_touch));  
				}
				setHome();
				return false;     
			}
		});

		ImageButton message = (ImageButton) findViewById(R.id.message);
		message.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {     
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					clearMenu();
					v.setBackgroundColor(getResources().getColor(R.color.dark_touch));  
				}
				setMessage();
				return false;     
			}
		});

		ImageButton friends = (ImageButton) findViewById(R.id.friends);
		friends.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {     
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					clearMenu();
					v.setBackgroundColor(getResources().getColor(R.color.dark_touch));  
				}
				setFriends();
				return false;     
			}
		});

		ImageButton search = (ImageButton) findViewById(R.id.search);
		search.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {     
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					clearMenu();
					v.setBackgroundColor(getResources().getColor(R.color.dark_touch));  
				}
				setSearch();
				return false;
			}
		});

		ImageButton settings = (ImageButton) findViewById(R.id.settings);
		settings.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {     
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					clearMenu();
					v.setBackgroundColor(getResources().getColor(R.color.dark_touch));  
				}
				setSettings();
				return false;     
			}
		});
	}

	private void setHome() {
		clearContent();
		LinearLayout tab_layout = (LinearLayout) findViewById(R.id.tab_layout);
		View home = View.inflate(this, R.layout.layout_home, null);
		tab_layout.addView(home);
		
		StatusesAPI api = new StatusesAPI(MainActivity.accessToken);
		api.homeTimeline(0, 0, 20, 1, false, FEATURE.PICTURE, false,  new RequestListener() {

			@Override
			public void onComplete(String response) {
				// TODO Auto-generated method stub
				Iterator<Weibo> iterator = JsonParser.parseWeibo(response);
				LinearLayout content_layout = (LinearLayout) findViewById(R.id.content_layout);
				while(iterator.hasNext()) {
					Weibo weibo = iterator.next();
					if (weibo.getRetweeted_status() != null) {
						View view = View.inflate(MainActivity.this, R.layout.layout_retweeted_weibo, null);
						User user = weibo.getUser();
						ImageView head = (ImageView) view.findViewById(R.id.retweeted_head);
						head.setImageURI(Uri.parse(user.getProfile_image_url()));
						Button name = (Button) view.findViewById(R.id.retweeted_name);
						if (user.getName() != null) {
							name.setText(user.getScreen_name() + " (" + user.getName() + ")");
						} else {
							name.setText(user.getScreen_name());
						}
						GridLayout share_list_layout = (GridLayout) view.findViewById(R.id.share_list_layout);
						share_list_layout.removeAllViewsInLayout();
						TextView text = new TextView(MainActivity.this);
						text.setText(weibo.getText());
						share_list_layout.addView(text);
						weibo = weibo.getRetweeted_status();
						while (weibo.getRetweeted_status() != null) {
							text = new TextView(MainActivity.this);
							text.setText(" //");
							share_list_layout.addView(text);
							Button retweeted_user = new Button(MainActivity.this);
							user = weibo.getUser();
							if (user.getName() != null) {
								retweeted_user.setText(user.getScreen_name() + " (" + user.getName() + ")");
							} else {
								retweeted_user.setText(user.getScreen_name());
							}
							share_list_layout.addView(retweeted_user);
							text = new TextView(MainActivity.this);
							text.setText(": " + weibo.getText());
							share_list_layout.addView(text);
							weibo = weibo.getRetweeted_status();
						}
						Button original_name = (Button) view.findViewById(R.id.retweeted_original_name);
						user = weibo.getUser();
						if (user.getName() != null) {
							original_name.setText(user.getScreen_name() + " (" + user.getName() + ")");
						} else {
							original_name.setText(user.getScreen_name());
						}
						TextView content = (TextView) view.findViewById(R.id.retweeted_content);
						content.setText(weibo.getText());
						ImageButton picture = (ImageButton) view.findViewById(R.id.retweeted_picture);
						picture.setImageURI(Uri.parse(weibo.getThumbnail_pic()));
						content_layout.addView(view);
						hasRetweeted = true;
					} else {
						View view = View.inflate(MainActivity.this, R.layout.layout_original_weibo, null);
						User user = weibo.getUser();
						ImageView head = (ImageView) view.findViewById(R.id.original_head);
						head.setImageURI(Uri.parse(user.getProfile_image_url()));
						Button name = (Button) view.findViewById(R.id.original_name);
						if (user.getName() != null) {
							name.setText(user.getScreen_name() + " (" + user.getName() + ")");
						} else {
							name.setText(user.getScreen_name());
						}
						TextView content = (TextView) view.findViewById(R.id.original_content);
						content.setText(weibo.getText());
						ImageButton picture = (ImageButton) view.findViewById(R.id.original_picture);
						picture.setImageURI(Uri.parse(weibo.getThumbnail_pic()));
						content_layout.addView(view);
						hasOriginal = true;
					}
				}
				Toast.makeText(MainActivity.this, "读取微博成功", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onIOException(IOException e) {
				// TODO Auto-generated method stub
				Toast.makeText(MainActivity.this, "读取微博失败", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onError(WeiboException e) {
				// TODO Auto-generated method stub
				Toast.makeText(MainActivity.this, "读取微博失败", Toast.LENGTH_SHORT).show();
			}
			
		});

		setHomeListener();
		if (hasOriginal) {
			setOriginalWeiboListener();
		}
		if (hasRetweeted) {
			setRetweetedWeiboListener();
		}
		hasOriginal = false;
		hasRetweeted = false;
	}

	private void setMessage() {
		clearContent();
		LinearLayout tab_layout = (LinearLayout) findViewById(R.id.tab_layout);
		View message = View.inflate(this, R.layout.layout_message, null);
		tab_layout.addView(message);
		setMessageListener();
	}

	private void setFriends() {
		clearContent();
		LinearLayout tab_layout = (LinearLayout) findViewById(R.id.tab_layout);
		View friends = View.inflate(this, R.layout.layout_friends, null);
		tab_layout.addView(friends);
		setFriendsListener();
	}

	private void setSearch() {
		clearContent();
		LinearLayout tab_layout = (LinearLayout) findViewById(R.id.tab_layout);
		View search = View.inflate(this, R.layout.layout_search, null);
		tab_layout.addView(search);
		setSearchListener();
	}

	private void setSettings() {
		clearContent();
		LinearLayout tab_layout = (LinearLayout) findViewById(R.id.tab_layout);
		View settings = View.inflate(this, R.layout.layout_settings, null);
		tab_layout.addView(settings);
		setSettingsListener();
	}


	private void setHomeListener() {

		ImageButton deliver = (ImageButton) findViewById(R.id.deliver);
		deliver.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {     
				if(event.getAction() == MotionEvent.ACTION_DOWN){   
					v.setBackgroundColor(getResources().getColor(R.color.touch));  
				}else if(event.getAction() == MotionEvent.ACTION_UP){     
					v.setBackgroundColor(getResources().getColor(R.color.theme));
					Intent intent = new Intent(MainActivity.this, DeliverActivity.class);
					startActivity(intent);
				}
				return false;     
			}
		});

		ImageButton refresh = (ImageButton) findViewById(R.id.refresh);
		refresh.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {     
				if(event.getAction() == MotionEvent.ACTION_DOWN){   
					v.setBackgroundColor(getResources().getColor(R.color.touch));  
				}else if(event.getAction() == MotionEvent.ACTION_UP){     
					v.setBackgroundColor(getResources().getColor(R.color.theme));
				}
				return false;     
			}
		});

	}

	private void setMessageListener() {
		Button at_me = (Button) findViewById(R.id.at_me);
		at_me.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {
				v.setBackgroundColor(getResources().getColor(R.color.touch));
				Button comment_me = (Button) findViewById(R.id.comment_me);
				comment_me.setBackgroundColor(getResources().getColor(R.color.theme));
				return false;
			}
		});

		Button comment_me = (Button) findViewById(R.id.comment_me);
		comment_me.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {
				v.setBackgroundColor(getResources().getColor(R.color.touch));
				Button at_me = (Button) findViewById(R.id.at_me);
				at_me.setBackgroundColor(getResources().getColor(R.color.theme));
				return false;
			}
		});
	}

	private void setFriendsListener() {
		Button followed_me = (Button) findViewById(R.id.followed_me);
		followed_me.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {
				v.setBackgroundColor(getResources().getColor(R.color.touch));
				Button following_me = (Button) findViewById(R.id.following_me);
				following_me.setBackgroundColor(getResources().getColor(R.color.theme));
				return false;
			}
		});

		Button following_me = (Button) findViewById(R.id.following_me);
		following_me.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {
				v.setBackgroundColor(getResources().getColor(R.color.touch));
				Button followed_me = (Button) findViewById(R.id.followed_me);
				followed_me.setBackgroundColor(getResources().getColor(R.color.theme));
				return false;
			}
		});
	}

	private void setSearchListener() {
		Button find_people = (Button) findViewById(R.id.find_people);
		find_people.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {     
				if(event.getAction() == MotionEvent.ACTION_DOWN){   
					((Button) v).setTextColor(getResources().getColor(R.color.white));
				}else if(event.getAction() == MotionEvent.ACTION_UP){     
					((Button) v).setTextColor(getResources().getColor(R.color.black));
				}
				return false;     
			}
		});

		Button find_weibo = (Button) findViewById(R.id.find_weibo);
		find_weibo.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {     
				if(event.getAction() == MotionEvent.ACTION_DOWN){   
					((Button) v).setTextColor(getResources().getColor(R.color.white));
				}else if(event.getAction() == MotionEvent.ACTION_UP){     
					((Button) v).setTextColor(getResources().getColor(R.color.black));
				}
				return false;     
			}
		});
	}

	private void setSettingsListener() {
		Button logout = (Button) findViewById(R.id.logout);
		logout.setOnTouchListener(new OnTouchListener(){
			@Override    
			public boolean onTouch(View v, MotionEvent event) {     
				if(event.getAction() == MotionEvent.ACTION_DOWN){   
					((Button) v).setTextColor(getResources().getColor(R.color.white));
				}else if(event.getAction() == MotionEvent.ACTION_UP){     
					((Button) v).setTextColor(getResources().getColor(R.color.black));
				}
				return false;     
			}
		});
	}
	
	private void setOriginalWeiboListener() {

		Button name = (Button) findViewById(R.id.original_name);
		name.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {     
				if(event.getAction() == MotionEvent.ACTION_DOWN){   
					v.setBackgroundColor(getResources().getColor(R.color.touch));  
				}else if(event.getAction() == MotionEvent.ACTION_UP){     
					v.setBackgroundColor(getResources().getColor(R.color.background));
				}
				return false;     
			}
		});

		Button comment = (Button) findViewById(R.id.original_comment);
		comment.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {     
				if(event.getAction() == MotionEvent.ACTION_DOWN){   
					((Button) v).setTextColor(getResources().getColor(R.color.white));
				}else if(event.getAction() == MotionEvent.ACTION_UP){     
					((Button) v).setTextColor(getResources().getColor(R.color.black));
				}
				return false;     
			}
		});

		Button share = (Button) findViewById(R.id.original_share);
		share.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {     
				if(event.getAction() == MotionEvent.ACTION_DOWN){   
					((Button) v).setTextColor(getResources().getColor(R.color.white));
				}else if(event.getAction() == MotionEvent.ACTION_UP){     
					((Button) v).setTextColor(getResources().getColor(R.color.black));
				}
				return false;     
			}
		});

		ImageButton like = (ImageButton) findViewById(R.id.original_like);
		like.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {     
				if(event.getAction() == MotionEvent.ACTION_DOWN){   
					v.setBackgroundColor(getResources().getColor(R.color.touch));  
				}else if(event.getAction() == MotionEvent.ACTION_UP){     
					v.setBackgroundColor(getResources().getColor(R.color.background));
				}
				return false;     
			}
		});

	}

	private void setRetweetedWeiboListener() {

		Button name = (Button) findViewById(R.id.retweeted_name);
		name.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {     
				if(event.getAction() == MotionEvent.ACTION_DOWN){   
					v.setBackgroundColor(getResources().getColor(R.color.touch));  
				}else if(event.getAction() == MotionEvent.ACTION_UP){     
					v.setBackgroundColor(getResources().getColor(R.color.background));
				}
				return false;     
			}
		});

		Button original_name = (Button) findViewById(R.id.retweeted_original_name);
		original_name.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {     
				if(event.getAction() == MotionEvent.ACTION_DOWN){   
					v.setBackgroundColor(getResources().getColor(R.color.touch));  
				}else if(event.getAction() == MotionEvent.ACTION_UP){     
					v.setBackgroundColor(getResources().getColor(R.color.background));
				}
				return false;     
			}
		});

		Button comment = (Button) findViewById(R.id.retweeted_comment);
		comment.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {     
				if(event.getAction() == MotionEvent.ACTION_DOWN){   
					((Button) v).setTextColor(getResources().getColor(R.color.white));
				}else if(event.getAction() == MotionEvent.ACTION_UP){     
					((Button) v).setTextColor(getResources().getColor(R.color.black));
				}
				return false;     
			}
		});

		Button share = (Button) findViewById(R.id.retweeted_share);
		share.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {     
				if(event.getAction() == MotionEvent.ACTION_DOWN){   
					((Button) v).setTextColor(getResources().getColor(R.color.white));
				}else if(event.getAction() == MotionEvent.ACTION_UP){     
					((Button) v).setTextColor(getResources().getColor(R.color.black));
				}
				return false;     
			}
		});

		ImageButton like = (ImageButton) findViewById(R.id.retweeted_like);
		like.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {     
				if(event.getAction() == MotionEvent.ACTION_DOWN){   
					v.setBackgroundColor(getResources().getColor(R.color.touch));  
				}else if(event.getAction() == MotionEvent.ACTION_UP){     
					v.setBackgroundColor(getResources().getColor(R.color.background));
				}
				return false;     
			}
		});

	}

	class AuthDialogListener implements WeiboAuthListener {

		@Override
		public void onComplete(Bundle values) {
			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");
			MainActivity.accessToken = new Oauth2AccessToken(token, expires_in);
			if (MainActivity.accessToken.isSessionValid()) {
				AccessTokenKeeper.keepAccessToken(MainActivity.this, accessToken);
				Toast.makeText(MainActivity.this, "认证成功", Toast.LENGTH_SHORT).show();
				init();
			}
		}

		@Override
		public void onError(WeiboDialogError e) {
			Toast.makeText(getApplicationContext(),
					"Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();
		}

		@Override
		public void onCancel() {
			Toast.makeText(getApplicationContext(), "Auth cancel",
					Toast.LENGTH_LONG).show();
		}

		@Override
		public void onWeiboException(WeiboException e) {
			Toast.makeText(getApplicationContext(),
					"Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
					.show();
		}

	}

}
